import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:material_dialogs/dialogs.dart';
import 'package:material_dialogs/shared/types.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/options_item.dart';
import 'package:tracker/pages/home/setting/dialog/command_dialog_interface.dart';
import 'package:tracker/pages/home/setting/model/remote_setting_list_resp.dart';
import 'package:tracker/theme/app_theme.dart';

class LowVoltageAlarmDialog implements CommandDialogInterface {
  late StateSetter _newSetState;

  final GlobalKey<ScaffoldState> scaffoldKey;
  final RemoteSettingData remoteSettingData;

  // 回调函数
  final Function(String cmdContent)? onConfirm;

  LowVoltageAlarmDialog({
    required this.scaffoldKey,
    required this.remoteSettingData,
    this.onConfirm,
  }) {
    // 初始化选项列表
    List<dynamic> enumObjs1 = json.decode(remoteSettingData.cmdFormat ?? '')[0]['enumObjs'];
    for (var element in enumObjs1) {
      final item = OptionsItem(label: element['value'], value: element['valueReal']);
      pickerOptions1.add(item);
    }
    const min = 90;
    const max = 900;
    for (int i = min; i <= max; i++) {
      var value = i / 10;
      // 保留1位小数
      value = double.parse(value.toStringAsFixed(1));
      final item2 = OptionsItem(label: '${value}V', value: value);
      final item3 = OptionsItem(label: '${value}V', value: value);
      pickerOptions2.add(item2);
      pickerOptions3.add(item3);
    }
    XLogger.info('pickerOptions2: ${pickerOptions2.length}');
    indexSelected2 = pickerOptions2.indexWhere((element) => element.value == 15);
    indexSelected3 = pickerOptions3.indexWhere((element) => element.value == 25);
  }

  int indexSelected1 = 1;
  final List<OptionsItem> pickerOptions1 = [];

  int indexSelected2 = 0;
  final List<OptionsItem> pickerOptions2 = [];

  int indexSelected3 = 0;
  final List<OptionsItem> pickerOptions3 = [];

  @override
  void show(BuildContext context) {
    return Dialogs.bottomMaterialDialog(
        context: context,
        isScrollControlled: true,
        customView: StatefulBuilder(builder: (newContext, newSetState) {
          _newSetState = newSetState;
          return Container(
            padding: const EdgeInsets.only(left: 20, right: 20, top: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  remoteSettingData.cmdName ?? '',
                  style: TextStyle(
                    fontSize: 18,
                    color: AppTheme.themeConfig.primaryTextColor,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(
                  height: 20,
                ),
                Row(
                  children: [
                    // 提示语
                    Expanded(
                      child: Text(
                        remoteSettingData.remark ?? '',
                        style: TextStyle(
                          fontSize: 16,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 12,
                ),
                Wrap(
                  children: [
                    Text(
                      '低电压报警: ',
                      style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryTextColor),
                    ),
                    GestureDetector(
                      onTap: () {
                        // 显示picker
                        Picker picker = Picker(
                          adapter: PickerDataAdapter(
                            data: pickerOptions1.map((e) => PickerItem(text: Text(e.label), value: e.value)).toList(),
                          ),
                          changeToFirst: true,
                          cancelText: '取消',
                          confirmText: '确定',
                          cancelTextStyle: const TextStyle(color: Colors.grey, fontSize: 16),
                          textAlign: TextAlign.left,
                          textStyle: const TextStyle(color: Colors.black, fontSize: 18),
                          selectedTextStyle: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 18),
                          columnPadding: const EdgeInsets.all(8.0),
                          onConfirm: (Picker picker, List value) {
                            XLogger.info('value: ${value}');
                            XLogger.info('picker.getSelectedValues(): ${picker.getSelectedValues()}');
                            newSetState(() {
                              indexSelected1 = value[0];
                            });
                          },
                        );
                        picker.selecteds = [indexSelected1];
                        picker.showModal(context);
                      },
                      child: _buildPickerTriggerText1(),
                    ),
                    Text(
                      ', 低于: ',
                      style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryTextColor),
                    ),
                    GestureDetector(
                      onTap: () {
                        // 显示picker
                        Picker picker = Picker(
                          adapter: PickerDataAdapter(
                            data: pickerOptions2.map((e) => PickerItem(text: Text(e.label), value: e.value)).toList(),
                          ),
                          changeToFirst: true,
                          cancelText: '取消',
                          confirmText: '确定',
                          cancelTextStyle: const TextStyle(color: Colors.grey, fontSize: 16),
                          textAlign: TextAlign.left,
                          textStyle: const TextStyle(color: Colors.black, fontSize: 18),
                          selectedTextStyle: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 18),
                          columnPadding: const EdgeInsets.all(8.0),
                          onConfirm: (Picker picker, List value) {
                            XLogger.info('value: ${value}');
                            XLogger.info('picker.getSelectedValues(): ${picker.getSelectedValues()}');
                            newSetState(() {
                              indexSelected2 = value[0];
                            });
                          },
                        );
                        picker.selecteds = [indexSelected2];
                        picker.showModal(context);
                      },
                      child: _buildPickerTriggerText2(),
                    ),
                    Text(
                      '报警, 大于: ',
                      style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryTextColor),
                    ),
                    GestureDetector(
                      onTap: () {
                        // 显示picker
                        Picker picker = Picker(
                          adapter: PickerDataAdapter(
                            data: pickerOptions3.map((e) => PickerItem(text: Text(e.label), value: e.value)).toList(),
                          ),
                          changeToFirst: true,
                          cancelText: '取消',
                          confirmText: '确定',
                          cancelTextStyle: const TextStyle(color: Colors.grey, fontSize: 16),
                          textAlign: TextAlign.left,
                          textStyle: const TextStyle(color: Colors.black, fontSize: 18),
                          selectedTextStyle: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 18),
                          columnPadding: const EdgeInsets.all(8.0),
                          onConfirm: (Picker picker, List value) {
                            XLogger.info('value: ${value}');
                            XLogger.info('picker.getSelectedValues(): ${picker.getSelectedValues()}');
                            newSetState(() {
                              indexSelected3 = value[0];
                            });
                          },
                        );
                        picker.selecteds = [indexSelected3];
                        picker.showModal(context);
                      },
                      child: _buildPickerTriggerText3(),
                    ),
                    Text(
                      '解除',
                      style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryTextColor),
                    ),
                  ],
                ),
              ],
            ),
          );
        }),
        customViewPosition: CustomViewPosition.BEFORE_TITLE,
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: const Text(
              '取消',
              style: TextStyle(color: Colors.grey, fontSize: 15),
            ),
          ),
          TextButton(
            onPressed: () {
              // 发送指令
              Navigator.pop(context);
              onConfirm?.call(getCommand());
            },
            child: Text(
              '发送指令',
              style: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 15),
            ),
          ),
        ]);
  }

  _buildPickerTriggerText1() {
    if (pickerOptions1.isNotEmpty && indexSelected1 >= 0 && indexSelected1 < pickerOptions1.length) {
      return Text(
        '${pickerOptions1[indexSelected1].label}',
        style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryColor),
      );
    }
    return Text('');
  }

  _buildPickerTriggerText2() {
    XLogger.info('indexSelected2: $indexSelected2');
    if (pickerOptions2.isNotEmpty && indexSelected2 >= 0 && indexSelected2 < pickerOptions2.length) {
      return Text(
        '${pickerOptions2[indexSelected2].label}',
        style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryColor),
      );
    }
    return Text('');
  }

  _buildPickerTriggerText3() {
    if (pickerOptions3.isNotEmpty && indexSelected3 >= 0 && indexSelected3 < pickerOptions3.length) {
      return Text(
        '${pickerOptions3[indexSelected3].label}',
        style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryColor),
      );
    }
    return Text('');
  }

  @override
  String getCommand() {
    // 拼接指令内容
    final content = pickerOptions1[indexSelected1].value;
    final content2 = pickerOptions2[indexSelected2].value;
    final content3 = pickerOptions3[indexSelected3].value;
    final content2Value = (content2 * 10).toInt();
    final content3Value = (content3 * 10).toInt();
    return '${remoteSettingData.cmdCode},${content},${content2Value},${content3Value}';
  }

  @override
  void updateCmdContent(String cmdContent) {
    if (cmdContent.isNotEmpty) {
      // 解析指令内容
      final cmdContentList = cmdContent.split(',');
      indexSelected1 = pickerOptions1.indexWhere((element) => element.value == cmdContentList[1]);
      if (cmdContentList.length >= 3) {
        var value = double.parse(cmdContentList[2]);
        if (isValidVoltageValue(value)) {
          indexSelected2 = pickerOptions2.indexWhere((element) => element.value == value / 10);
        }
      }
      if (cmdContentList.length >= 4) {
        var value = double.parse(cmdContentList[3]);
        if (isValidVoltageValue(value)) {
          indexSelected3 = pickerOptions3.indexWhere((element) => element.value == value / 10);
        }
      }
    }
  }

  /// 判断是否是有效的电压值
  bool isValidVoltageValue(double doubleValue) {
    if (doubleValue < 90 || doubleValue > 900) {
      return false;
    }
    return true;
  }
}
